/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System.Collections.Generic;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Windows.Controls;
using System;
using System.IO;
using System.Diagnostics;


#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif
namespace Oceanside
{
    /// <summary>
    /// Interaction logic for PageLogin.xaml
    /// </summary>
    public partial class PageSystemConfigurationImp : PageImpBaseClass
    {
        Grid gridControls;

        /// <summary>
        /// Constructor
        /// </summary>
        public PageSystemConfigurationImp(
            UIElementCollection stackPcontChild,
            DbLinkedTextBox tbStoreId,
            DbLinkedTextBox tbBusinessDtartTime,
            DbLinkedTextBox rL1,
            DbLinkedTextBox rL2,
            DbLinkedTextBox rL3,
            DbLinkedTextBox rL4,
            DbLinkedTextBox rLTop,
            DbLinkedTextBox rLBottom,
            ComboBox cbScreenTimeout,
            ComboBox cbPrintTimeout,
            ComboBox cbBusinesStartDayOfWeek,
            Button bSetBusinessDayStart,
            Button bCalibrateTouch,
            Grid gridControls,
            GroupBox mainGroupBox)
        {
            this.ButtonNumber = "15";
            this.ButtonLabelText = "System Configuration";
            this.gridControls = gridControls;

            RegisterSaveMeGroupBoxes(null, mainGroupBox);
            RegisterUiElementsList(stackPcontChild);

            ///Add all text boxes to the list.
            mTextBoxesList.Add(tbStoreId);
            mTextBoxesList.Add(tbBusinessDtartTime);
            mTextBoxesList.Add(rL1);
            mTextBoxesList.Add(rL2);
            mTextBoxesList.Add(rL3);
            mTextBoxesList.Add(rL4);
            mTextBoxesList.Add(rLTop);
            mTextBoxesList.Add(rLBottom);

            mListOfControlsToDisableInAllModes.Add(tbStoreId);
            mDeleteEntityIsDisabled = true;
            mNewEntityIsDisabled = true;
            mDeleteGroupIsDisabled = true;
            mNewGroupIsDisabled = true;

            ListofComboboxes.Add(cbScreenTimeout);
            ListofComboboxes.Add(cbPrintTimeout);
            ListofComboboxes.Add(cbBusinesStartDayOfWeek);

            mListOfControlsToDisableInNonEditMode.Add(cbScreenTimeout);
            mListOfControlsToDisableInNonEditMode.Add(cbPrintTimeout);
            mListOfControlsToDisableInNonEditMode.Add(cbBusinesStartDayOfWeek);
            mListOfControlsToDisableInNonEditMode.Add(bCalibrateTouch);
            mListOfControlsToDisableInNonEditMode.Add(bSetBusinessDayStart);


            bCalibrateTouch.Click += new System.Windows.RoutedEventHandler(bCalibrateTouch_Click);
            bSetBusinessDayStart.Click += new System.Windows.RoutedEventHandler(bSetBusinessDayStart_Click);


            mEntityAddDeleteLoggingEnabled = true;
        }


        void bSetBusinessDayStart_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                var q = from SYS in Context.SYSCONFIGS select SYS;
                if (q.Any())
                {
                    SYSCONFIG selected = q.First();
                    if (selected != null)
                    {
                        TimePicker dtp = new TimePicker(false);
                        dtp.ShowDialog();
                        if (TimePicker.LastResponse == UserResponse.YES)
                        {
                            selected.BusinessDayStartTime = TimePicker.LastStartSelectedDateTime;
                            Context.SaveChanges();
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_REPORT_ERROR, exc);
            }
        }

        void bCalibrateTouch_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            ///Try to get the registry key that indicates where the touch configuration utility is
            ///located at.  After getting the key, see if the file exists.  If it does, launch
            ///the utility.
            if (String.IsNullOrEmpty(Constants.TouchConfigUtil))
            {
                UMD.ShowGuiMessageSTASafe_NOTHROW("The touch configuration registry value is not set.");
            }
            else if (!File.Exists(Constants.TouchConfigUtil))
            {
                UMD.ShowGuiMessageSTASafe_NOTHROW("The touch configuration registry value is set to " + Constants.TouchConfigUtil +
                    " however that file does not exist on the system.");
            }
            else
            {
                ///The registry key is set and the file exists.  Launch the util.
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = Constants.TouchConfigUtil;
                System.Diagnostics.Process process = Process.Start(startInfo);

                if (!process.HasExited)
                {
                    PosWindow.MainPosWindow.WindowState = System.Windows.WindowState.Minimized;
                    process.WaitForExit(60000);
                }
                if (!process.HasExited)
                {
                    process.Kill();
                }

                PosWindow.MainPosWindow.WindowState = System.Windows.WindowState.Maximized;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        override public List<EntityObject> GetEntityObjectSet()
        {
            try
            {
                return new List<EntityObject>(Context.SYSCONFIGS.ToList());
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        public override void Navigating()
        {
            gridControls.DataContext = null;
            base.Navigating();
        }

        /// <summary>
        /// 
        /// </summary>
        public void LoadObservableList()
        {
            ///Create the query object.
            var query = from SYSCONFIG in Context.SYSCONFIGS select SYSCONFIG;
            List<SYSCONFIG> systemConfigList = query.ToList();
            if (systemConfigList.Count != 0)
            {
                gridControls.DataContext = systemConfigList[0];
            }
            else
            {
                SYSCONFIG sysCfg = new SYSCONFIG();
                sysCfg.UserMagSwipeToken = "%OCEANSIDE SOFTWARE?;8889686232";
                sysCfg.ReceiptLine1 = "";
                sysCfg.ReceiptLine2 = "";
                sysCfg.ReceiptLine3 = "";
                sysCfg.ReceiptLine4 = "";
                sysCfg.TopReceiptMessage = "";
                sysCfg.BottomReceiptMessage = "";
                sysCfg.BusinessDayOfWeekStartDay = "Monday";
                sysCfg.BusinessDayStartTime = DateTime.Now;
                sysCfg.IncludeDiscountsInNetSales = true;
                sysCfg.ScreenLockTimeout = 120;
                sysCfg.PrintQueueTimeout = 120;
                sysCfg.ForceOrderOnScreenTimeout = true;
                sysCfg.StoreId = Guid.NewGuid();
                sysCfg.DbVersion = 1;
                Context.SYSCONFIGS.AddObject(sysCfg);
                Context.SaveChanges();

                List<SYSCONFIG> sysCfgList = Context.SYSCONFIGS.ToList();
                gridControls.DataContext = sysCfgList[0];
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override EntityObject GetSelectedEntityObject()
        {
            SYSCONFIG selected = null;
            if (gridControls.DataContext != null)
            {
                selected = gridControls.DataContext as SYSCONFIG;
            }
            return selected;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        public override void UpdateUsersEntitySource()
        {
            LoadObservableList();
        }
    }
}
